package com.hbx.msmservice.controller;

import com.hbx.commonutils.R;
import com.hbx.msmservice.service.MsmService;
import com.hbx.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author hbx
 * @Date 2023/10/14 14:45
 */
@Api(tags = {"阿里云短信服务和邮件验证"})
@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public R sendMsg(@PathVariable String phone){
        //1.从redis中获取验证码如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2.如果redis获取不到，进行阿里云发送验证码
        //通过工具类获取4位验证码
        code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend = msmService.send(param,phone);
        if(isSend){
            //发送成功后，将验证码放到redis中
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok().message("发送成功");
        }
        return R.error().message("发送失败");
    }

    /**
     * 发送邮件
     * @param mail
     * @return
     */
    @GetMapping("/sendqq/{mail}")
    public R sendMail(@PathVariable String mail){
        String code = RandomUtil.getFourBitRandom();
        boolean isSend = msmService.sendMail(mail,code);
        if(isSend){
            return R.ok().message("发送成功");
        }
        return R.error().message("发送失败");
    }
}
